﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LOGISTCBUS.Entities;
using LOGISTCBUS.DAO;
using LOGISTCBUS.Entities.Enums;

namespace LOGISTCBUS.WebUI.Controllers
{
    [HandleError(View = "Error")]
    public class CustomerController : Controller
    {
        public ActionResult Index()
        {
            var user = (User)this.Session["user"];
            if (user == null)
                return RedirectToAction(@"LogOut", @"Account");
            return View();
        }

        public ActionResult Edit(int? id)
        {
            var userLogged = (User)this.Session["user"];
            if (userLogged == null)
                return RedirectToAction(@"LogOut", @"Account");

            if (id.HasValue)
            {
                var customer = new CustomerDAO().selectById(Convert.ToInt32(id));
                this.ViewData[@"customer"] = customer == null ? new Customer() : customer;
            }

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Save(int id)
        {
            var c = id > 0 ? new CustomerDAO().selectById(id) : new Customer();
            var aux = true;

            if (!String.IsNullOrEmpty(Request.Params["name"]))
                c.Name = Request.Params["name"];
            if (!String.IsNullOrEmpty(Request.Params["rg"]))
                c.RG = Request.Params["rg"];
            if (!String.IsNullOrEmpty(Request.Params["cpf"]))
                c.CPF = Request.Params["cpf"];
            if (!String.IsNullOrEmpty(Request.Params["birthdate"]))
                c.BirthDate = Convert.ToDateTime(Request.Params["birthdate"]);
            if (!String.IsNullOrEmpty(Request.Params["address"]))
                c.Address = Request.Params["address"];
            if (!String.IsNullOrEmpty(Request.Params["id_city"]))
                c.City = new City() { Id = Convert.ToInt32(Request.Params["id_city"]) };
            if (!String.IsNullOrEmpty(Request.Params["phone"]))
                c.Phone = Request.Params["phone"];
            if (!String.IsNullOrEmpty(Request.Params["cellular"]))
                c.Cellular = Request.Params["cellular"];
            if (!String.IsNullOrEmpty(Request.Params["id_sex"]))
                c.Sex = (ESex)Convert.ToInt32(Request.Params["id_sex"]);
            if (!String.IsNullOrEmpty(Request.Params["description"]))
                c.Description = Request.Params["description"];

            if (c.Id > 0)
                aux = new CustomerDAO().update(c);
            else
                aux = new CustomerDAO().insert(c);

            var obj = new
            {
                success = aux,
                message = "Cliente salvo com sucesso!"
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Search()
        {
            var page = String.IsNullOrEmpty(Request.Params[@"page"]) ? 1 : Convert.ToInt32(Request.Params[@"page"]);
            var name = String.IsNullOrEmpty(Request.Params[@"name"]) ? string.Empty : Request.Params[@"name"].ToString();
            var pageSize = MvcApplication.pageSize;
            var customers = new CustomerDAO().select(name, page, pageSize);
            var count = new CustomerDAO().getCount(name);
            var totalPages = (count < pageSize) ? 1 : Math.Ceiling(Convert.ToDecimal(count) / pageSize);
            var lst = new List<object>();

            foreach (var c in customers)
            {
                var ct = c.City != null ? new CityDAO().selectById(c.City.Id) : new City();
                lst.Add(new
                {
                    Id = c.Id,
                    Name = c.Name,
                    RG = c.RG,
                    CPF = c.CPF,
                    City = ct != null ? ct.FullName : string.Empty,
                    Sex = c.Sex != null && c.Sex > 0 ? WebHelpers.GetEnumDescription(c.Sex) : string.Empty,
                });
            }

            var obj = new
            {
                data = lst,
                currpage = page,
                totalpages = totalPages,
                totalrecords = count
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Delete()
        {
            var id = String.IsNullOrEmpty(Request.Params[@"id"]) ? 0 : Convert.ToInt32(Request.Params[@"id"]);
            var page = String.IsNullOrEmpty(Request.Params[@"page"]) ? 1 : Convert.ToInt32(Request.Params[@"page"]);
            var aux = true;

            if (id > 0)
            {
                var c = new Customer() { Id = id };
                aux = new CustomerDAO().delete(c);
            }

            var obj = new
            {
                Message = "Registro removido com sucesso!",
                Success = aux,
                Page = page
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult DeleteAll()
        {
            var values = Request.Form["ids"].Split(new String[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            var aux = true;

            var lst = new List<Customer>();
            foreach (var val in values)
                if (!String.IsNullOrEmpty(val))
                    lst.Add(new Customer() { Id = Convert.ToInt32(val) });
            aux = new CustomerDAO().delete(lst);

            var obj = new
            {
                Message = "Registro(s) removido(s) com sucesso!",
                Success = aux
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult LoadCities()
        {
            var idState = String.IsNullOrEmpty(Request.Params[@"idState"]) ? 0 : Convert.ToInt32(Request.Params[@"idState"]);
            var lst = new List<object>();

            if (idState > 0)
            {
                var cities = new CityDAO().selectByState(idState);

                foreach (var c in cities)
                {
                    lst.Add(new
                    {
                        Id = c.Id,
                        Name = c.Name
                    });
                }
            }

            return Json(lst);
        }
    }
}
